package edu.sctu;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class UserAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("gbk");
        resp.setCharacterEncoding("gbk");

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String sql = "insert into t_users(userName,password) values('" + userName + "','" + password + "') ";

        DBConnection dbConnection = new DBConnection();
        try {
            Connection connection = dbConnection.getConnection();
            Statement statement = connection.createStatement();
            statement.execute(sql);

            statement.close();
            dbConnection.closeConnection(connection);

            PrintWriter out = resp.getWriter();
            out.print(userName + "");
            out.println("添加成功！");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        req.getRequestDispatcher("/useAdd.jsp").forward(req, resp);
    }

}
